var API = require('wechat-api');
var redis = require('../redis/redis');
var wxConfig = require('../config/config');
var apiUrlConfig = require('../config/config');
var request = require('request');

module.exports = {
    
    // apiUrl:'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='+wxConfig.AppID+'&secret='+wxConfig.Secret,

    getAccessTokenByAppId:function(res)
    {
        this.checkExpire(wxConfig.appid,function(accessToken)
        {
            if(!accessToken)
            {
                request(apiUrlConfig.accessTokenUrl,function(err, response, data){
                    
                    if (!err && response.statusCode == 200) {
        
                        redis.setAccessToken(wxConfig.appid, data, function(data){
                            res.end(JSON.stringify({
                                token:data
                            }));
                        });
        
                    }                        
                });  
            }else
            {
                res.end(JSON.stringify({
                    token:accessToken
                }));
            }

        });
    },

    getAccessToken: function()
    {
        return new Promise(function(resolve, reject){
            redis.get(wxConfig.appid,function(accessToken)
            {
                if(!accessToken)
                {
                    request(apiUrlConfig.accessTokenUrl,function(err, response, data){
                        
                        if (!err && response.statusCode == 200) {
            
                            redis.setAccessToken(wxConfig.appid, data, function(data){
                                resolve(JSON.parse(data));
                            });
            
                        }                        
                    });  
                }else
                {
                    resolve(JSON.parse(accessToken));
                }
    
            });

        });
    },

    checkExpire:function(appid,callback)
    {
        redis.get(appid,function(res){
            callback(res);
        });
    }
}